package dashboard

import (
	"oa-rest/common"
	"oa-rest/models/message"
	"oa-rest/models/task"
)

func getMessagesByReceiver(username string) (messages []*message.Message, err error) {
	if err = common.DB.Where("receiver = ? and status=1", username).Desc("priority").Desc("id").Find(&messages); err != nil {
		return
	}
	return
}

// 这里既要有登录用户发起的数据，还应该包含需要他审批的数据（节点流转到他这了）
func getTasksByReceiver(username string) (tasks []*task.Task, err error) {
	// 1.需要当前登录用户审批的tasks
	// todo 还得排序（截止日期剩余天数）
	var tasks1 []*task.Task
	if err = common.DB.SQL("select * from task where id in (select t1.task_id  from task_node_item t1 left join task_node t2 on t1.node_id= t2.id  where t1.username = ? and t1.status = 1 and t2.status=2) ORDER BY ABS(EXTRACT(EPOCH FROM (end_time::timestamp - CURRENT_TIMESTAMP))) ASC", username).Find(&tasks1); err != nil {
		return
	}

	// 2.当前用户发起的tasks
	var tasks2 []*task.Task
	if err = common.DB.Where("operator = ? and status=1", username).Desc("id").Find(&tasks2); err != nil {
		return
	}
	tasks = append(tasks, tasks1...)
	// 遍历 tasks2，如果不在 tasks1 里，就加入
	for _, t2 := range tasks2 {
		found := false
		for _, t1 := range tasks1 {
			if t1.Id == t2.Id {
				found = true
				break
			}
		}
		if !found {
			tasks = append(tasks, t2)
		}
	}

	for _, t := range tasks {
		// 查询模板节点列表
		if err := common.DB.Where("task_id = ?", t.Id).Asc("id").Find(&t.NodeList); err != nil {
			return nil, err
		}
		// 查询每个节点的审批人
		for _, node := range t.NodeList {
			if err := common.DB.Where("node_id = ?", node.Id).Find(&node.ItemList); err != nil {
				return nil, err
			}
		}
	}

	return
}
